﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using FPPrinter.Models.Printers;
using FPPrinter.Models.SourceFiles;
using FPPrinter.utiles;

namespace FPPrinter.Models
{
    
    public class Sys
    {
        private string configfile = "settings.json";

         static Sys _ins=new Sys();
        public static Sys Instance{get{return _ins;}}
        private Sys( )
        {

            var anti = AntiObject.Instance;
            SourceFileManager = anti.GetSourceFileManager();
            PrinterManager = anti.GetPrinterManager();
            OptimzedDocManager = anti.GetOptimzedDocManager();

            PrinterManager.ScanForPrinter();


            ReadConifg();
            
            //lastest folder

            //resore the laste printer name

        }

        public ConfigSys Config { get; set; } = new ConfigSys();

        private void ReadConifg()
        {

            if (!File.Exists(configfile)) SaveCoinfig();
            var txt=File.ReadAllText(configfile);
            Config = txt.ToObject<ConfigSys>();


            LoadHis(Config.LastestFolder);

        }

        private void LoadHis(string fd)
        {
            try
            {
                if (!string.IsNullOrEmpty(Config.LastestFolder))
                {
                    string[] pdfFiles = Directory.GetFiles(fd, "*.pdf", SearchOption.AllDirectories);
                    this.SourceFileManager.Analysis(pdfFiles);
                
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            
        }

        private void SaveCoinfig()
        {
            var json = Config.ToJson();
            File.WriteAllText(configfile, json);
        }

        public ISourceFileManager SourceFileManager { get; set; }  
        public IPrinterManager PrinterManager { get; private set; }  
        public IOptimizedDocManager OptimzedDocManager { get; set; }
        public string SelectedPrinterName
        {
            get=>Config.LastestPrinter  ;
            set
            {
                Config.LastestPrinter = value;
                PrinterManager.SelectPrinter(value);
            }
        }

        public void OptimizeFiles()
        {
            
             "至少一个pdf".Required(  SourceFileManager.Files.Count()>0 ) ;  
             var sourceFiles = SourceFileManager.Files;
             OptimzedDocManager.GenerateDocs(sourceFiles);

             Config.LastestFolder = SourceFileManager.RootLatest;
        }

        public void Exist()
        {
            SaveCoinfig();
            SourceFileManager.Dispose();
        }


        public void ClearAllFiles()
        {
            
            SourceFileManager.Clear();
            OptimzedDocManager.Clear();

        }
    }
}